package com.qiaoba.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiaoba.auth.entity.SysLoginLog;
import com.qiaoba.auth.entity.param.SysLoginLogParam;
import com.qiaoba.auth.mapper.SysLoginLogMapper;
import com.qiaoba.auth.service.SysLoginLogService;
import com.qiaoba.common.base.entity.param.TimeParam;
import com.qiaoba.common.base.exception.ServiceException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 登陆日志 服务层实现
 *
 * @author ailanyin
 * @date 2023-09-24 10:41:57
 */
@Service
@RequiredArgsConstructor
public class SysLoginLogServiceImpl implements SysLoginLogService {

    private final SysLoginLogMapper sysLoginLogMapper;

    @Override
    public void insert(SysLoginLog sysLoginLog) {
        sysLoginLogMapper.insert(sysLoginLog);
    }

    @Override
    public List<SysLoginLog> selectList(SysLoginLogParam param) {
        return sysLoginLogMapper.selectList(param2Wrapper(param));
    }

    @Override
    public int delete(List<String> loginIds) {
        return sysLoginLogMapper.deleteBatchIds(loginIds);
    }

    @Override
    public void delLog(TimeParam param) {
        if (ObjectUtil.isEmpty(param.getBeginTime()) || ObjectUtil.isEmpty(param.getEndTime())) {
            throw new ServiceException("开始时间-结束时间必填！");
        }
        QueryWrapper<SysLoginLog> wrapper = new QueryWrapper<>();
        wrapper.lambda().between(SysLoginLog::getLoginTime, param.getBeginTime(), param.getEndTime());
        sysLoginLogMapper.delete(wrapper);
    }

    private QueryWrapper<SysLoginLog> param2Wrapper(SysLoginLogParam param) {
        QueryWrapper<SysLoginLog> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .orderByDesc(SysLoginLog::getLoginTime)
                .between(ObjectUtil.isNotEmpty(param.getBeginTime()) && ObjectUtil.isNotEmpty(param.getEndTime()),
                        SysLoginLog::getLoginTime, param.getBeginTime(), param.getEndTime())
                .like(StrUtil.isNotBlank(param.getUsername()), SysLoginLog::getUsername, param.getUsername())
                .like(StrUtil.isNotBlank(param.getIp()), SysLoginLog::getIp, param.getIp())
                .eq(StrUtil.isNotBlank(param.getStatus()), SysLoginLog::getStatus, param.getStatus());
        return wrapper;
    }
}
